package modules.sys.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import luxing.common.controller.BaseController;
import luxing.common.service.CloudStorageService;
import luxing.constant.StorageConfig;
import luxing.exception.BusinessException;
import luxing.util.DateUtil;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/umeditorController")
public class UmeditorController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UmeditorController.class);

	@Autowired
	private CloudStorageService cloudStorageService;

	/**
	 * 上传图片
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "upload")
	@ResponseBody
	public Map<String, Object> upload(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("upfile");// 获取上传文件对象
			if (file.getContentType().contains("image") && file.getSize() < 5000000) {
				// 文件名后缀
				String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
				String picName = DateUtil.dateToStr(new Date(), "yyyyMMdd") + DateUtil.dateToStr(new Date(), "HHmmssS")
						+ UUID.randomUUID().toString().replaceAll("-", "").substring(0, 5) + "." + suffix;
				cloudStorageService.upload(file.getBytes(), StorageConfig.bucketUmeditor, picName);
				result.put("state", "SUCCESS");
				result.put("url", picName);
			}
		} catch (Exception e) {
			logger.error(e);
			throw new BusinessException(e);
		}
		return result;
	}
}
